# -*- coding: UTF-8 -*-
import os
import sys
import codecs
import xlrd
import platform

reload(sys)  
sys.setdefaultencoding('utf8')

global doc_path
global sever_path
global client_path

sysstr = platform.system()
doc_path=''
sever_path=''
client_path=''

if sysstr=="Darwin":
    doc_path = sys.path[0]+"/Doc"
    sever_path = sys.path[0]+"/Sever"
    # client_path = sys.path[0]+"\Client"
    client_path = sys.path[0].replace('/Doc','/')+"Assets/Resources/Data"
elif sysstr=="Windows":
    doc_path = sys.path[0]+"\Doc"
    sever_path = sys.path[0]+"\Sever"
    client_path = sys.path[0].replace('\Doc','\\')+"Assets/Resources/Data"

if not os.path.exists(sever_path):
        os.makedirs(sever_path)
        print "Make Sever Dir!"

if not os.path.exists(client_path):
        os.makedirs(client_path)
        print "Make Client Dir!"

if not os.path.exists(doc_path):
        os.makedirs(doc_path)
        print "No Doc path , Make Doc Dir, No File To Handle!"
        exit(0)

def FloatToString (aFloat):
    if type(aFloat) != float:
        return ""
    strTemp = str(aFloat)
    strList = strTemp.split(".")
    if len(strList) == 1 :
        return strTemp
    else:
        if strList[1] == "0" :
            return strList[0]
        else:
            return strTemp

def TableToJson(table,jsonFileName):
    nrows = table.nrows
    ncols = table.ncols

    # write sever data
    f = codecs.open(sever_path+"/"+jsonFileName,"w","utf-8")
    f.write(u"{\n\"list\":[\n")
    for r in range(nrows-1):
        if(r==0):
            continue
        f.write(u"\t{ ")
        for c in range(ncols):
            strCellValue = u""
            CellObj = table.cell_value(r+1,c)

            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)

            key=table.cell_value(1,c)
            if key.split(':')[1]=='c':
                continue
            
            strTmp = u"\""  + key.split(':')[0] + u"\":"+ strCellValue

            if c< ncols-1:
                strTmp += u", "

            f.write(strTmp)
        f.write(u" }")
        if r < nrows-2:
            f.write(u",")
        f.write(u"\n")
    f.write(u"\t]\n}\n")
    f.close()
    print "Create Severdata ",jsonFileName,"Succed!"

    # write client data
    f = codecs.open(client_path+"/"+jsonFileName,"w","utf-8")
    f.write(u"{\n\"list\":[\n")
    for r in range(nrows-1):
        if(r==0):
            continue
        f.write(u"\t{ ")
        for c in range(ncols):
            strCellValue = u""
            CellObj = table.cell_value(r+1,c)
            if type(CellObj) == unicode:
                strCellValue = CellObj
            elif type(CellObj) == float:
                strCellValue = FloatToString(CellObj)
            else:
                strCellValue = str(CellObj)

            key=table.cell_value(1,c)
            if key.split(':')[1]=='s':
                continue

            strTmp = u"\""  + key.split(':')[0] + u"\":"+ strCellValue

            if c< ncols-1:
                strTmp += u", "
            f.write(strTmp)
        f.write(u" }")
        if r < nrows-2:
            f.write(u",")
        f.write(u"\n")
    f.write(u"\t]\n}\n")
    f.close()

    print "Create Clientdata ",jsonFileName,"Succed!"
    return

def ReadExcel(fileName):
    data = xlrd.open_workbook(fileName)
    tables = data.sheets()

    for table in tables:
        table.name+=".json"
        TableToJson(table,table.name)

def GetFileList(dir, fileList):
    newDir = dir
    if os.path.isfile(dir):
        fileList.append(dir)
    elif os.path.isdir(dir):  
        for s in os.listdir(dir):
            if os.path.splitext(s)[1] != '.xlsx':
                continue
            newDir=os.path.join(dir,s)
            GetFileList(newDir, fileList)  
    return fileList
 
fileList = GetFileList(doc_path, [])
for i in range(len(fileList)):
    if sysstr=="Darwin":
        print fileList[i].replace(doc_path+"/", str(i)+"_")
    elif sysstr=="Windows":
        print fileList[i].replace(doc_path+"\\", str(i)+"_")

index=raw_input("input 'a' to handle all files,or chosse a file with id:")

if index!="a" :
    ReadExcel(fileList[int(index)]);
else:
    for i in xrange(len(fileList)):
        ReadExcel(fileList[i]);




